package br.com.goals.tableedit.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.sql.DataSource;

import br.com.goals.tableedit.model.FieldConfig;
import br.com.goals.tableedit.model.HtmlSelect;
import br.com.goals.tableedit.model.HtmlSelectOption;

public class ComboFactory {
	DataSource dataSource;
	FieldConfig fieldConfig;
	public ComboFactory(DataSource dataSource,FieldConfig fieldConfig){
		this.dataSource=dataSource;
		this.fieldConfig = fieldConfig;
	}
	public void from(String tableName,String pk,String label,String orderBy) throws SQLException{
		HtmlSelect htmlSelect = new HtmlSelect(tableName,pk,label);
		ArrayList<HtmlSelectOption> options = new ArrayList<HtmlSelectOption>();
		Connection con = this.dataSource.getConnection();
		PreparedStatement st = con.prepareStatement("Select "+pk+","+label+" From "+tableName+" order by "+orderBy);
		ResultSet rs = st.executeQuery();
		while(rs.next()){
			String vLabel = "";
			if(label.indexOf(',')!=-1){
				String[] labels = label.split(",");
				for(String lbl:labels){
					vLabel += rs.getObject(lbl.trim())+" ";
				}
				options.add(new HtmlSelectOption(rs.getObject(pk).toString(),vLabel));
			}else{
				options.add(new HtmlSelectOption(rs.getObject(pk).toString(),rs.getObject(label).toString()));
			}
		}
		rs.close();
		st.close();
		con.close();
		htmlSelect.setOptions(options);
		this.fieldConfig.htmlSelect=htmlSelect;
	}
	/**
	 * Ordena pelo label
	 * @param tableName nome da tabela
	 * @param pk id da tabela
	 * @param label parte visivel do opt
	 * @throws SQLException
	 */
	public void from(String tableName,String pk,String label) throws SQLException{
		from(tableName,pk,label,label);
	}
}
